﻿using System;
using Microsoft.SharePoint;
using VH.SharePoint.Api.Entensions;
using VH.SharePoint.Api.Helpers;

namespace VH.SharePoint.Api
{

    public abstract class BlogItem
    {
        internal SPListItem Item;
        public Int32 Id {
            get { return Item.ID; }
        }

        public String Title {
            get { return Item.GetFieldValue<String>(SPBuiltInFieldId.Title); ; }
            set { Item.SetFieldValue<String>(value, SPBuiltInFieldId.Title); }
        }

        public DateTime Created {
            get { return Item.GetFieldValue<DateTime>(SPBuiltInFieldId.Created); }
        }

        public DateTime Modified {
            get { return Item.GetFieldValue<DateTime>(SPBuiltInFieldId.Modified); }
        }

        public SPUser CreatedBy {
            get
            {
                var value = Item.GetFieldValue<SPFieldUserValue>(SPBuiltInFieldId.Author);
                return value.User;
            }
        }
        public SPUser ModifiedBy
        {
            get
            {
                var value = Item.GetFieldValue<SPFieldUserValue>(SPBuiltInFieldId.Modified_x0020_By);
                return value.User;
            }
        }

        public String Url {
            get { return Item.GetFieldValue<String>(SPBuiltInFieldId.EncodedAbsUrl); }
        }

        public SPFile File {
            get { return Item.File; }
        }


        protected BlogItem(SPListItem item)
        {
            var file = item.File;
            Item = file==null?item:file.Item;
        }

        public virtual void Update()
        {
            using (new SPUnsafeUpdate(Item.Web))
            {
                try
                {

                    if (File != null)
                        File.Update();
                    Item.Update();

                }
                catch (SPException ex)
                {
                    if (ex.Message.Contains("has been modified by"))
                    {
                        Item.SystemUpdate(false);
                    }
                    else
                    {
                        throw;
                    }
                }
            }

        }

        public static implicit operator SPListItem(BlogItem item)
        {
            return item.Item;
        }
        
    }
}